function Replay() {
    this.id = 1;
    this.count = 0;
}

Replay.create = function() {
    gDBWorld.insert({_id:'_replay_autoid', ai:1}, function(err, result){}); 
}

Replay.prototype = {
    init : function(callback) {
        gDBWorld.findOne({_id : '_replay_autoid'}, {}, function(err, doc){
            if( doc ) {
                this.id = doc.ai + 10000;
                callback && callback(true);
            }else{
                callback && callback(false);
            }
        }.bind(this));
    },

    addReplay : function(battle) {
        this.count += 1;
        this.id += 1; 
        if( this.count > 1000 ) {
            this.count = 0;
            gDBWorld.update({_id: '_replay_autoid'}, {$set:{ai:this.id}}, function(err, doc){});
        }
        
        var replayKey = util.format('replay_%d_%d', config.ServerId, this.id);
        gCache.set(replayKey, JSON.stringify(battle));

        return this.id;
    },
    
    getReplay : function(id, callback) {
        var replayKey = util.format('replay_%d_%d', config.ServerId, id);
        
        gCache.get(replayKey, function(err, doc) {
            callback && callback( err ? null : doc);
        });
    },

    deleteReplay : function(id) {
        //gCache.del('replay_'+id);
    },
}

exports.get = function(req, resp, onHandled) {
    do{
        gReplay.getReplay(req.args.id, function(battle){
            if( battle ) {
                resp.data.battle = battle;
            }
            onHandled();
        });
        
        return;
    }while(false);

    onHandled();
}

exports.Replay = Replay;
